package com.pesking.core.sqlparser.processor;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.pesking.core.parameter.Parameter;
import com.pesking.core.sqlparser.parameter.SqlParameter;
import com.pesking.core.sqlparser.parameter.SqlParameterProcessor;
import com.pesking.core.util.DateUtils;
import com.pesking.core.util.StringUtils;

public class EndDateSqlParameterHandler extends SqlParameterProcessor {
	@Override
	public String getTitle() {
		return "结束日期参数";
	}

	@Override
	public String getDescription() {
		return this.getTitle() + " 在指定日期基础上加上1";
	}

	@Override
	public void handle(StringBuilder sbSQL, Parameter parameter, List<SqlParameter> processors,SqlParameter sqlParameter) {
		sbSQL.append("?");
		processors.add(sqlParameter);
	}

	@Override
	public void setParameter(PreparedStatement ps, Parameter parameter, int index,SqlParameter sqlParameter) throws SQLException {
		String value = parameter.getParameter(sqlParameter.getName());
		if (!StringUtils.isBlank(value)) {
			value = value.trim();
			Date d = DateUtils.string2Date(value);
			Timestamp ts = new Timestamp(d.getTime());
			d = DateUtils.dateDiff(ts, 1, DateUtils.DIFF_DAY);
			java.sql.Date dd = new java.sql.Date(d.getTime());
			ps.setDate(index, dd);
		}
		else {
			ps.setNull(index, java.sql.Types.DATE);
		}
	}

	public void setParameter(Connection connection, PreparedStatement ps, int index, String paramValue)
			throws SQLException {

	}

	@Override
	public List<String> getSqlParameterType() {
		return Arrays.asList(new String []{"ED","END_DATE"});
	}
}
